package org.example.sys.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.launch
import org.example.sys.R
import org.example.sys.bean.Book
import org.example.sys.bean.BookItem
import org.example.sys.databinding.FragmentHomeBinding
import org.example.sys.ui.dashboard.DetailFragment
import org.example.sys.ui.util.Hooks
import org.example.sys.ui.util.IdleOnScrollListener
import org.example.sys.ui.util.RecyclerItemClickListener


class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!
    private val homeViewModel by lazy { ViewModelProvider(this)[HomeViewModel::class.java] }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding.root
        val recyclerView: RecyclerView = binding.recyclerView
        this.context?.let {
            val bookList = mutableListOf<Book>()
            val adapter = BookAdapter(it, bookList)
            recyclerView.adapter = adapter
            recyclerView.layoutManager = LinearLayoutManager(it);
            recyclerView.addOnScrollListener(IdleOnScrollListener(object : Hooks {
                override fun onBottom() {
                    homeViewModel.get(bookList.size)
                }

                override fun onTop() {
                }
            }))
            recyclerView.addOnItemTouchListener(
                RecyclerItemClickListener(context, recyclerView,
                    object : RecyclerItemClickListener.OnItemClickListener {
                        override fun onItemClick(view: View?, position: Int) {
                            view?.apply {
                                val bundle = Bundle();
                                bundle.putParcelable(DetailFragment.TAG, bookList[position])
                                val navController = Navigation.findNavController(this)
                                navController.apply {
                                    popBackStack();
                                    navigate(R.id.home_to_book_detail, bundle);
                                }
                            }
                        }

                        override fun onItemLongClick(view: View?, position: Int) {
                            val bookItem = BookItem(bookList.get(position), position)
                            val builder = AlertDialog.Builder(activity!!)
                            builder.setTitle(R.string.title_dialog_delete)
                            builder.setItems(R.array.button_selection) { dialog, which ->
                                when (which) {
                                    0 -> {
                                        homeViewModel.deleteBook(bookItem)
                                    }
                                }
                                dialog.dismiss()
                            }
                            builder.show()
                        }
                    })
            );

            lifecycleScope.launch {
                homeViewModel.idLiveData.observe(viewLifecycleOwner) { bookItem ->
                    bookItem?.apply {
                        adapter.list.removeAt(position)
                        adapter.notifyItemRemoved(bookItem.position)
                    }
                };


                homeViewModel.bookLiveData.observe(viewLifecycleOwner) { books ->
                    books?.apply {
                        val firstLoad = bookList.size == 0
                        bookList.addAll(bookList.size, books)
                        adapter.notifyItemRangeInserted(
                            if (firstLoad) 0 else bookList.size - 1,
                            books.size
                        )
                    }
                }
                homeViewModel.loadStateLiveData.observe(viewLifecycleOwner) { state ->
                    when (state) {
                        HomeViewModel.State.Loading -> {
                            binding.swipeRefreshLayout.isRefreshing = true
                        }

                        HomeViewModel.State.NotLoading -> {
                            binding.swipeRefreshLayout.isRefreshing = false
                        }

                        HomeViewModel.State.Clear -> {
                            bookList.clear()
                        }

                        else -> {
                            Toast.makeText(
                                context,
                                getString(R.string.title_some_things_wrong),
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                }
            }

            binding.swipeRefreshLayout.setOnRefreshListener {
                homeViewModel.start()
            }
            homeViewModel.start()
        }
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}